package org.jeecg.modules.hc.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.hc.entity.HcAfterSales;
import org.jeecg.modules.hc.entity.HcMerchant;
import org.jeecg.modules.hc.entity.HcMerchantSettlement;
import org.jeecg.modules.hc.enums.HcMerchantSettlementTypeEnum;
import org.jeecg.modules.hc.enums.HcSyncMerchantSettlementTypeEnum;
import org.jeecg.modules.hc.service.IHcAfterSalesService;
import org.jeecg.modules.hc.service.IHcMerchantService;
import org.jeecg.modules.hc.service.IHcMerchantSettlementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Description: 商户结算
 * @Author: jeecg-boot
 * @Date: 2023-02-17
 * @Version: V1.0
 */
@Api(tags = "商户结算")
@RestController
@RequestMapping("/hc/hcMerchantSettlement")
@Slf4j
public class HcMerchantSettlementController extends JeecgController<HcMerchantSettlement, IHcMerchantSettlementService> {
    @Autowired
    private IHcMerchantSettlementService hcMerchantSettlementService;

    @Autowired
    private IHcMerchantService hcMerchantService;

    @Autowired
    private IHcAfterSalesService hcAfterSalesService;

    @Value("${wx.pay.privateKeyPath}")
    private String privatekeypath ;

    @AutoLog(value = "根据商户id统计结算")
    @ApiOperation("根据商户id统计结算")
    @GetMapping(value = "/syncMerchantSettlementById")
    public Result<?> syncMerchantSettlementById(@RequestParam(name = "merchantId") String merchantId) throws ParseException {
        List list = hcMerchantSettlementService.syncMerchantSettlement(merchantId, HcSyncMerchantSettlementTypeEnum.ALL);
        return Result.OK(list);
    }

    @ApiOperation("清除商户openid")
    @GetMapping(value = "/clearOpenId")
    public Result<?> clearOpenIdByMerchantId(@RequestParam(name = "merchantId") String merchantId){
        hcMerchantService.clearMerchantOpenId(merchantId);
        return Result.OK("清除成功");
    }

    @ApiOperation("周三自动结算商户设置")
    @AutoLog(value = "周三自动结算商户设置")
    @GetMapping(value = "/changeAutoSettle")
    public Result<?> changeAutoSettle(@RequestParam(name = "merchantId") String merchantId,
                                      @RequestParam(name = "autoSettle") Boolean autoSettle){
        Integer integer = hcMerchantService.changeAutoSettle(merchantId, autoSettle);
        if (integer>0){
            return Result.OK("设置成功");
        }else {
            return Result.OK("设置失败");
        }
    }

    @AutoLog(value = "所有商户进行统计结算")
    @ApiOperation("所有商户进行统计结算")
    @GetMapping(value = "/syncMerchantSettlementAll")
    public Result<?> syncMerchantSettlementAll() throws ParseException {
        List result = new ArrayList();
        List<HcMerchant> hcMerchantList = hcMerchantService.list();

        for (HcMerchant hcMerchant : hcMerchantList) {
            result.addAll(hcMerchantSettlementService.syncMerchantSettlement(hcMerchant.getId(), HcSyncMerchantSettlementTypeEnum.ALL));
        }
        return Result.OK(result);
    }

    @GetMapping(value = "/queryRecordListByLogin")
    public Result<List<HcMerchantSettlement>> queryRecordListByLogin() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        List<HcMerchantSettlement> list = hcMerchantSettlementService.list(
                new LambdaQueryWrapper<HcMerchantSettlement>()
                        .eq(HcMerchantSettlement::getMerchantId, sysUser.getId())
                        .eq(HcMerchantSettlement::getType, HcMerchantSettlementTypeEnum.SETTLED)
                        .orderByDesc(HcMerchantSettlement::getSettlementDate)
        );

        return Result.OK(list);
    }

    @ApiOperation("商户自动结算")
    @Transactional
    @PostMapping(value = "/doSettlementNew")
    public Result<?> doSettlementNew(@RequestBody List<HcMerchantSettlement> hcMerchantSettlementList) throws Exception {
        //商家批次单号 长度 1~32
        String outNo = UuidUtils.getUUID();
        //openId
        String openId = "";
        //备注
        String remarks = "";
        //转账总金额
        BigDecimal totalSettlementAmount = new BigDecimal(0);
        for (HcMerchantSettlement hcMerchantSettlement : hcMerchantSettlementList) {
            HcMerchant hcMerchant = hcMerchantService
                    .getById(hcMerchantSettlementService
                            .getById(hcMerchantSettlement.getId()).getMerchantId());
            if (hcMerchant.getStoreName().contains("•")){
                String storeName = hcMerchant.getStoreName().replace("•", "");
                remarks = storeName +":";
            }else {
                remarks = hcMerchant.getStoreName()+":";
            }
            totalSettlementAmount = totalSettlementAmount.add(new BigDecimal(String.valueOf(hcMerchantSettlement.getSettlementAmount())));
            openId = hcMerchant.getOpenId();
            hcMerchantSettlementService.updateById(new HcMerchantSettlement()
                    .setId(hcMerchantSettlement.getId())
                    .setSettlementAmount(hcMerchantSettlement.getSettlementAmount())
                    .setOutNo(outNo)
                    .setType(HcMerchantSettlementTypeEnum.SETTLING)
            );
        }
        //转账批次
        BigDecimal divide = totalSettlementAmount.divide(new BigDecimal(1999),0,BigDecimal.ROUND_UP);
       //超2000分批结算
        if (totalSettlementAmount.compareTo(new BigDecimal(2000)) == 1){
            int flag = 0;
            do {
                flag+=1;
                String remark = "";
                if (totalSettlementAmount.compareTo(new BigDecimal(1999)) == 1){
                    //商家批次单号 长度 1~32
                    String outNo1 = IdUtil.getSnowflake(0, 0).nextIdStr();
                    // 转账备注
                    remark = " 转账:1999元("+ flag+"/"+divide+")";
                    hcMerchantService.transferToMerchant(openId, new BigDecimal(1999), outNo1,remarks +remark);
                    totalSettlementAmount = totalSettlementAmount.subtract(new BigDecimal(1999));
                }else {
                    // 转账备注
                    remark = " 转账"+totalSettlementAmount+"元("+ flag+"/"+divide+")";
                    hcMerchantService.transferToMerchant(openId, totalSettlementAmount, outNo,remarks + remark);
                    totalSettlementAmount = totalSettlementAmount.subtract(new BigDecimal(1999));
                }
            }while (totalSettlementAmount.compareTo(new BigDecimal(0)) == 1);
        }else {
            //未超2000的直接结算
            remarks += totalSettlementAmount+"元";
            //转账给商户
            hcMerchantService.transferToMerchant(openId, totalSettlementAmount, outNo,remarks);
        }
        return Result.OK("结算已受理");
    }

    @AutoLog(value = "进行商家结算")
    @PostMapping(value = "/doSettlement")
    @Transactional
    public Result<?> doSettlement(@RequestBody List<HcMerchantSettlement> hcMerchantSettlementList) throws WxErrorException, NotFoundException, InterruptedException {
        for (HcMerchantSettlement hcMerchantSettlement : hcMerchantSettlementList) {
            hcMerchantSettlementService.updateById(new HcMerchantSettlement()
                    .setId(hcMerchantSettlement.getId())
                    .setSettlementAmount(hcMerchantSettlement.getSettlementAmount())
                    .setType(HcMerchantSettlementTypeEnum.SETTLED)
            );
        }
        return Result.OK("结算成功");
    }

    @GetMapping(value = "/queryRecordListById")
    public Result<List<HcMerchantSettlement>> queryRecordListById(String merchantId) {
        List<HcMerchantSettlement> list = hcMerchantSettlementService.list(
                new LambdaQueryWrapper<HcMerchantSettlement>()
                        .eq(HcMerchantSettlement::getMerchantId, merchantId)
                        .ne(HcMerchantSettlement::getType, HcMerchantSettlementTypeEnum.UNSETTLED)
                        .orderByDesc(HcMerchantSettlement::getUpdateTime, HcMerchantSettlement::getSettlementDate)
        );
        return Result.OK(list);
    }

    @GetMapping(value = "/queryListById")
    public Result<List<HcMerchantSettlement>> queryListById(String merchantId) {
        List<HcMerchantSettlement> list = hcMerchantSettlementService.list(
                new LambdaQueryWrapper<HcMerchantSettlement>()
                        .eq(HcMerchantSettlement::getMerchantId, merchantId)
                        .in(HcMerchantSettlement::getType, Arrays.asList(HcMerchantSettlementTypeEnum.UNSETTLED
                                ,HcMerchantSettlementTypeEnum.SETTLING
                                ,HcMerchantSettlementTypeEnum.FAIL))
                        .orderByDesc(HcMerchantSettlement::getSettlementDate)
        );
        return Result.OK(list);
    }

    @ApiOperation("商户结算列表New")
    @GetMapping(value = "/queryListByIdNew")
    public Result<List<HcMerchantSettlement>> queryListByIdNew(String merchantId) {
        List<HcMerchantSettlement> list = hcMerchantSettlementService.list(
                new LambdaQueryWrapper<HcMerchantSettlement>()
                        .eq(HcMerchantSettlement::getMerchantId, merchantId)
                        .in(HcMerchantSettlement::getType, Arrays.asList(HcMerchantSettlementTypeEnum.UNSETTLED
                                ,HcMerchantSettlementTypeEnum.SETTLING
                                ,HcMerchantSettlementTypeEnum.FAIL))
                        .orderByDesc(HcMerchantSettlement::getSettlementDate)
        );
        list.forEach( l -> {
            if (l.getSettlementDate() != null){
                String beginTime = "";
                String endTime = "";
                Calendar instance = Calendar.getInstance();
                instance.setTime(l.getSettlementDate());
                instance.add(Calendar.DAY_OF_MONTH, -1);
                beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";
                instance.add(Calendar.DAY_OF_MONTH, +1);
                endTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:00";
                final BigDecimal[] finalSettlementAmount = {new BigDecimal(String.valueOf(l.getSettlementAmount()))};
                //根据id查询售后信息
//                List<HcAfterSales> list1 = hcAfterSalesService.list(
//                        new LambdaQueryWrapper<HcAfterSales>()
//                                .eq(HcAfterSales::getMerchantId, merchantId)
//                                .between(HcAfterSales::getCreateTime,beginTime,endTime)
//                );
//                if (list1!=null){
//                    list1.forEach( l1 -> {
//                        if (l1.getDeductMerchantAmount() != null)
//                            finalSettlementAmount[0] =  finalSettlementAmount[0].subtract(new BigDecimal(String.valueOf(l1.getDeductMerchantAmount())));
//                    });
//                }
                l.setSettlementAmount(finalSettlementAmount[0]);
            }
        });
        return Result.OK(list);
    }
    @GetMapping(value = "/querySumById")
    public Result<?> querySumById(String merchantId) {
        Map<String, Object> map = hcMerchantSettlementService.getMap(new QueryWrapper<HcMerchantSettlement>()
                .select("ifnull(sum(if(TYPE = 'unsettled', SETTLEMENT_AMOUNT, 0)), 0) as 'all'")
                .eq("MERCHANT_ID", merchantId)
        );

        JSONObject result = new JSONObject();
        result.put("all", map.get("all"));
        result.put("settled", map.get("settled"));
        result.put("change", map.get("change"));
        result.put("unsettled", map.get("unsettled"));

        return Result.OK(result);
    }
    @GetMapping(value = "/querySumByIdNew")
    public Result<?> querySumByIdNew(String merchantId) {
        Map<String, Object> map = hcMerchantSettlementService.getMap(new QueryWrapper<HcMerchantSettlement>()
                .select("ifnull(sum(if(TYPE in ('unsettled','settling','fail'), SETTLEMENT_AMOUNT, 0)), 0) as 'all'")
                .eq("MERCHANT_ID", merchantId)
        );

        JSONObject result = new JSONObject();
        BigDecimal bigDecimal = (BigDecimal) map.get("all");
        result.put("all", bigDecimal);
        result.put("settled", map.get("settled"));
        result.put("change", map.get("change"));
        result.put("unsettled", map.get("unsettled"));

//        //找到未结算的订单
//        List<HcMerchantSettlement> list = hcMerchantSettlementService.list(
//                new LambdaQueryWrapper<HcMerchantSettlement>()
//                        .eq(HcMerchantSettlement::getMerchantId, merchantId)
//                        .in(HcMerchantSettlement::getType, Arrays.asList(HcMerchantSettlementTypeEnum.UNSETTLED
//                                ,HcMerchantSettlementTypeEnum.SETTLING
//                                ,HcMerchantSettlementTypeEnum.FAIL))
//                        .orderByDesc(HcMerchantSettlement::getSettlementDate)
//        );
//        //遍历订单找到需要减去的金额
//        final BigDecimal[] finalSettlementAmount = {new BigDecimal(0)};
//        list.forEach( l -> {
//            if (l.getSettlementDate() != null){
//                String beginTime = "";
//                String endTime = "";
//                Calendar instance = Calendar.getInstance();
//                instance.setTime(l.getSettlementDate());
//                beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";
//                instance.add(Calendar.DAY_OF_MONTH, +1);
//                endTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:00";
//                //根据id查询售后信息
//                List<HcAfterSales> list1 = hcAfterSalesService.list(
//                        new LambdaQueryWrapper<HcAfterSales>()
//                                .eq(HcAfterSales::getMerchantId, merchantId)
//                                .between(HcAfterSales::getCreateTime,beginTime,endTime)
//                );
//                if (list1!=null){
//                    list1.forEach( l1 -> {
//                        if (l1.getDeductMerchantAmount() != null)
//                            finalSettlementAmount[0] =  finalSettlementAmount[0].add(l1.getDeductMerchantAmount());
//                    });
//                }
//            }
//        });
//        bigDecimal = bigDecimal.subtract(finalSettlementAmount[0]);
//        result.put("all", bigDecimal);
        return Result.OK(result);
    }


    /**
     * 分页列表查询
     *
     * @param hcMerchantSettlement
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "商户结算-分页列表查询")
    @ApiOperation(value = "商户结算-分页列表查询", notes = "商户结算-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<HcMerchantSettlement>> queryPageList(HcMerchantSettlement hcMerchantSettlement,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<HcMerchantSettlement> page = new Page<>(pageNo, pageSize);
        IPage<HcMerchantSettlement> pageList = hcMerchantSettlementService.pageList(page, hcMerchantSettlement);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param hcMerchantSettlement
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "商户结算-分页列表查询")
    @ApiOperation(value = "商户结算-分页列表查询", notes = "商户结算-分页列表查询")
    @GetMapping(value = "/listNew")
    public Result<IPage<HcMerchantSettlement>> queryPageListNew(HcMerchantSettlement hcMerchantSettlement,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<HcMerchantSettlement> page = new Page<>(pageNo, pageSize);
        IPage<HcMerchantSettlement> pageList = hcMerchantSettlementService.pageList(page, hcMerchantSettlement);
        pageList.getRecords().forEach(l -> {
            HcMerchantSettlement hcMerchantSettlement1 = hcMerchantSettlementService.getOne(new QueryWrapper<HcMerchantSettlement>()
                    .select("ifnull(sum(if(TYPE in ('unsettled','settling','fail'), SETTLEMENT_AMOUNT, 0)), 0) as 'SETTLEMENT_AMOUNT'")
                    .eq("MERCHANT_ID", l.getMerchantId())
            );
            final BigDecimal[] settlementAmount = {hcMerchantSettlement1.getSettlementAmount()};
            //找到未结算的订单
            List<HcMerchantSettlement> list = hcMerchantSettlementService.list(
                    new LambdaQueryWrapper<HcMerchantSettlement>()
                            .eq(HcMerchantSettlement::getMerchantId, l.getMerchantId())
                            .in(HcMerchantSettlement::getType, Arrays.asList(HcMerchantSettlementTypeEnum.UNSETTLED
                                    ,HcMerchantSettlementTypeEnum.SETTLING
                                    ,HcMerchantSettlementTypeEnum.FAIL))
                            .orderByDesc(HcMerchantSettlement::getSettlementDate)
            );
            //遍历订单找到需要减去的金额
            final BigDecimal[] finalSettlementAmount = {new BigDecimal(0)};
            list.forEach( l1 -> {
                if (l1.getSettlementDate() != null){
                    String beginTime = "";
                    String endTime = "";
                    Calendar instance = Calendar.getInstance();
                    instance.setTime(l1.getSettlementDate());
                    beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";
                    instance.add(Calendar.DAY_OF_MONTH, +1);
                    endTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:00";
                    //根据id查询售后信息
                    List<HcAfterSales> list2 = hcAfterSalesService.list(
                            new LambdaQueryWrapper<HcAfterSales>()
                                    .eq(HcAfterSales::getMerchantId, l.getMerchantId())
                                    .between(HcAfterSales::getCreateTime,beginTime,endTime)
                    );
                    if (list2!=null){
                        list2.forEach( l2 -> {
                            if (l2.getDeductMerchantAmount() != null)
                                //需要减去的总和
                                finalSettlementAmount[0] =  finalSettlementAmount[0].add(l2.getDeductMerchantAmount());
                        });
                    }
                }
            });
//            l.setSettlementAmount(settlementAmount[0].subtract( finalSettlementAmount[0]));
            l.setSettlementAmount(settlementAmount[0]);
        });
        return Result.OK(pageList);
    }


    /**
     * 添加
     * @param hcMerchantSettlement
     * @return
     */
    @AutoLog(value = "商户结算-添加")
    @ApiOperation(value = "商户结算-添加", notes = "商户结算-添加")
    //@RequiresPermissions("org.jeecg.modules:hc_merchant_settlement:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody HcMerchantSettlement hcMerchantSettlement) {
        hcMerchantSettlement.setType(HcMerchantSettlementTypeEnum.CHANGE);
        hcMerchantSettlement.setUpdateTime(new Date());
        hcMerchantSettlementService.save(hcMerchantSettlement);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hcMerchantSettlement
     * @return
     */
//    @AutoLog(value = "商户结算-编辑")
//    @ApiOperation(value = "商户结算-编辑", notes = "商户结算-编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_merchant_settlement:edit")
//    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody HcMerchantSettlement hcMerchantSettlement) {
        hcMerchantSettlementService.updateById(hcMerchantSettlement);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
//    @AutoLog(value = "商户结算-通过id删除")
//    @ApiOperation(value = "商户结算-通过id删除", notes = "商户结算-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:hc_merchant_settlement:delete")
//    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hcMerchantSettlementService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @returnqueryRecordListById
     */
//    @AutoLog(value = "商户结算-批量删除")
//    @ApiOperation(value = "商户结算-批量删除", notes = "商户结算-批量删除")
    //@RequiresPermissions("org.jeecg.modules:hc_merchant_settlement:deleteBatch")
//    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hcMerchantSettlementService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "商户结算-通过id查询")
    @ApiOperation(value = "商户结算-通过id查询", notes = "商户结算-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<HcMerchantSettlement> queryById(@RequestParam(name = "id", required = true) String id) {
        HcMerchantSettlement hcMerchantSettlement = hcMerchantSettlementService.getById(id);
        if (hcMerchantSettlement == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hcMerchantSettlement);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hcMerchantSettlement
     */
    //@RequiresPermissions("org.jeecg.modules:hc_merchant_settlement:exportXls")
//    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcMerchantSettlement hcMerchantSettlement) {
        return super.exportXls(request, hcMerchantSettlement, HcMerchantSettlement.class, "商户结算");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("hc_merchant_settlement:importExcel")
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcMerchantSettlement.class);
    }

    //压缩字符串的长度
    private String YsString(String originalString) throws IOException {
        // 使用 Gzip 压缩算法对字符串进行压缩
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
        gzipOutputStream.write(originalString.getBytes("UTF-8"));
        gzipOutputStream.close();
        byte[] compressedBytes = outputStream.toByteArray();

        // 使用 Gzip 压缩算法对字符串进行解压缩
        ByteArrayInputStream inputStream = new ByteArrayInputStream(compressedBytes);
        GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
        ByteArrayOutputStream uncompressedStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = gzipInputStream.read(buffer)) > 0) {
            uncompressedStream.write(buffer, 0, length);
        }
        String uncompressedString = uncompressedStream.toString("UTF-8");
        return uncompressedString ;
    }
}
